<?php
namespace app\http;

use think\console\Command;
use think\console\Input;
use think\console\Output;

/**
 * Class Timer
 * @package app\http
 * 启动: php think async_tcp:start
 */
class AsyncTcpClient extends Command
{
    protected $client;

    // 命令行配置函数
    //tp5 命令行配置详细用法 https://blog.csdn.net/kelinfeng16/article/details/88549717
    protected function configure()
    {
        // setName 设置命令行名称
        // setDescription 设置命令行描述
        $this->setName('async_tcp:client')->setDescription('Start Async TCP Client!');
    }

    // 设置命令返回信息
    protected function execute(Input $input, Output $output)
    {
        // 实例化客户端
        $this->client = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);

        // 注册回调函数
        $this->client->on('Connect', [$this, 'onConnect']);
        $this->client->on('Receive', [$this, 'onReceive']);
        $this->client->on('Error', [$this, 'onError']);
        $this->client->on('Close', [$this, 'onClose']);

        //发起连接
        $this->client->connect('127.0.0.1', 9501, 0.5);
    }

    // 注册连接成功回调
    public function onConnect(\swoole_client $cli)
    {
        $cli->send("hello world\n");
    }

    // 注册数据接收回调
    public function onReceive(\swoole_client $cli, $data)
    {
        echo "message sending\n";
        echo "Received: ".$data."\n";
    }

    // 注册连接失败回调
    public function onError(\swoole_client $cli)
    {
        echo "Connect failed\n";
    }

    // 注册连接关闭回调
    public function onClose(\swoole_client $cli)
    {
        echo "Connection close\n";
    }
}